#include "sql_compiler_cpp/Lexer.h"
#include "sql_compiler_cpp/Parser.h"
#include "sql_compiler_cpp/ExecutionPlan.h"
#include "sql_compiler_cpp/PredicatePushdownOptimizer.h"
#include <iostream>
#include <memory>

using namespace MiniDB;

/**
 * 测试谓词下推优化器的效果
 */
void testPredicatePushdown() {
    std::cout << "=== 谓词下推优化器测试 ===" << std::endl;

    // 测试SQL查询
    std::string sql = "SELECT id, name FROM users WHERE age > 20 AND name = 'Alice';";

    std::cout << "测试SQL: " << sql << std::endl;
    std::cout << std::endl;

    // 词法分析
    Lexer lexer(sql);
    auto tokens = lexer.tokenize();

    std::cout << "词法分析结果:" << std::endl;
    for (const auto& token : tokens) {
        if (token.type != TokenType::EOF_TOKEN) {
            std::cout << "  " << token.toString() << std::endl;
        }
    }
    std::cout << std::endl;

    // 语法分析
    Parser parser(tokens);
    auto statements = parser.parse();

    if (statements.empty()) {
        std::cerr << "解析失败，没有生成语句" << std::endl;
        return;
    }

    std::cout << "语法分析成功，生成 " << statements.size() << " 个语句" << std::endl;
    std::cout << std::endl;

    // 创建符号表并添加测试表信息
    SymbolTable symbol_table;
    TableInfo users_table("users");

    // 添加列定义
    ColumnInfo id_col("id", DataType::INT, 0, false, true); // PRIMARY KEY
    ColumnInfo name_col("name", DataType::VARCHAR, 50, false, false); // NOT NULL
    ColumnInfo age_col("age", DataType::INT, 0, true, false);
    ColumnInfo email_col("email", DataType::VARCHAR, 100, true, false);

    users_table.addColumn(id_col);
    users_table.addColumn(name_col);
    users_table.addColumn(age_col);
    users_table.addColumn(email_col);

    symbol_table.addTable(users_table);

    // 生成初始执行计划
    PlanGenerator plan_generator(symbol_table);
    auto initial_plan = plan_generator.generatePlan(statements);

    std::cout << "初始执行计划:" << std::endl;
    initial_plan->print();
    std::cout << std::endl;

    // 禁用谓词下推，生成对比计划
    plan_generator.enablePredicatePushdown(false);
    auto no_optimization_plan = plan_generator.generatePlan(statements);

    std::cout << "未优化执行计划:" << std::endl;
    no_optimization_plan->print();
    std::cout << std::endl;

    // 启用谓词下推，生成优化计划
    plan_generator.enablePredicatePushdown(true);
    auto optimized_plan = plan_generator.generatePlan(statements);

    std::cout << "谓词下推优化后执行计划:" << std::endl;
    optimized_plan->print();
    std::cout << std::endl;

    // 测试另一个更复杂的查询
    std::string complex_sql = "SELECT id, name FROM users WHERE age > 20 AND department = 'IT';";
    std::cout << "复杂查询测试SQL: " << complex_sql << std::endl;

    Lexer complex_lexer(complex_sql);
    auto complex_tokens = complex_lexer.tokenize();

    Parser complex_parser(complex_tokens);
    auto complex_statements = complex_parser.parse();

    if (!complex_statements.empty()) {
        auto complex_plan = plan_generator.generatePlan(complex_statements);
        std::cout << "复杂查询优化后执行计划:" << std::endl;
        complex_plan->print();
    }

    std::cout << "\n=== 谓词下推优化器测试完成 ===" << std::endl;
}

/**
 * 演示谓词下推的优化效果
 */
void demonstrateOptimization() {
    std::cout << "\n=== 谓词下推优化效果演示 ===" << std::endl;

    // 模拟一个典型的数据查询场景
    std::cout << "场景: 查询年龄大于20岁的用户" << std::endl;
    std::cout << "表大小: 假设有10000条记录，其中2000条符合age > 20的条件" << std::endl;
    std::cout << std::endl;

    std::cout << "未优化执行流程:" << std::endl;
    std::cout << "1. 扫描表中全部10000条记录" << std::endl;
    std::cout << "2. 对每条记录应用WHERE条件过滤" << std::endl;
    std::cout << "3. 筛选出2000条符合条件的记录" << std::endl;
    std::cout << "4. 应用SELECT投影操作" << std::endl;
    std::cout << "总代价: 10000次记录读取 + 2000次过滤操作" << std::endl;
    std::cout << std::endl;

    std::cout << "谓词下推优化后的执行流程:" << std::endl;
    std::cout << "1. 在扫描过程中直接应用age > 20过滤条件" << std::endl;
    std::cout << "2. 只读取符合条件的记录（约2000条）" << std::endl;
    std::cout << "3. 应用SELECT投影操作" << std::endl;
    std::cout << "总代价: 2000次记录读取 + 2000次过滤操作" << std::endl;
    std::cout << std::endl;

    std::cout << "性能提升:" << std::endl;
    std::cout << "- I/O操作减少: 80% (10000 -> 2000)" << std::endl;
    std::cout << "- 内存使用减少: 80%" << std::endl;
    std::cout << "- 查询响应时间显著改善" << std::endl;
    std::cout << std::endl;
}

int main() {
    try {
        testPredicatePushdown();
        demonstrateOptimization();
    } catch (const std::exception& e) {
        std::cerr << "测试过程中发生错误: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
